package com.cuanbo.dualscreenteachzhu.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.cuanbo.dualscreenteachzhu.activity.MainActivity;
import com.cuanbo.dualscreenteachzhu.base.App;
import com.cuanbo.dualscreenteachzhu.bean.AtyInfo;

import java.util.List;

public class AppUtil {
    /**
     * 计时时间，单位秒s
     */
    private static int openRuiQuAppNum = 0;
    /**
     * 超时时间，单位秒s
     */
    public static int timeout = 60;

    /**
     * 打开App
     *
     * @param context 上下文对象
     */
    public static void open(Context context) {
        try {
            AtyInfo atyInfo= App.getShowingActivity();
            if(atyInfo==null){
                App.getInstance().closeAllAty();
                ActivityUtil.openNewAty(App.getInstance(), MainActivity.class);
            }/*else{
                Activity aty=atyInfo.getAty();
                if(aty instanceof Main2Activity){
                    if(atyInfo.getState()!=AtyInfo.STATE_RESUME){
                        App.getInstance().closeAllAty();
                        ActivityUtil.openNewAty(App.getInstance(),Main2Activity.class);
                    }
                }
            }*/
        } catch (Exception e) {
            LogUtil.addError("================拉起APP失败=================");
            LogUtil.addError(e);
            LogUtil.addError("=================================");
        }
    }

    /**
     * 每隔timeout秒拉一次App
     *
     * @param context 上下文对象
     */
    public static void timer(Context context) {
        try {
            //LogUtil.add("timer", "当前计时=" + openRuiQuAppNum + " 超时时间=" + timeout, "拉起其他应用");
            if (openRuiQuAppNum >= timeout) {
                openRuiQuAppNum = 0;
                open(context);
            } else {
                openRuiQuAppNum++;
            }
        } catch (Exception e) {
        }
    }

    /**
     * 判断是否安装了某应用
     *
     * @param context     上下文对象
     * @param packageName 安装包的名称
     */
    public static boolean isAppInstalled(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {

            for (int i = 0; i < pinfo.size(); i++) {

                if (pinfo.get(i).packageName.equals(packageName)) {
                    return true;
                }

            }

        }
        return false;
    }


}
